﻿using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Windows;
using WxMpApiDemo.Services;

namespace WxMpApiDemo
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public IServiceProvider ServiceProvider { get; private set; }

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            // 创建服务集合
            var services = new ServiceCollection();

            // 配置服务
            ConfigureServices(services);

            // 构建ServiceProvider
            ServiceProvider = services.BuildServiceProvider();

            //使用IServiceProvider创建一个MainWindow
            var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
            mainWindow.Show();
        }

        /// <summary>
        /// 配置服务
        /// </summary>
        /// <param name="services"></param>
        private void ConfigureServices(IServiceCollection services)
        {
            // 1. 注册主窗口和其他视图模型/服务
            services.AddTransient<MainWindow>();

            //// 2. 关键：注册 IHttpClientFactory 并添加 HTTP 客户端服务
            //services.AddHttpClient();

            //// 3. 你也可以注册命名或类型化的客户端
            //// 例如，为 GitHub API 注册一个特定客户端
            //services.AddHttpClient("GitHubClient", client =>
            //{
            //    client.BaseAddress = new Uri("https://api.github.com/");
            //    client.DefaultRequestHeaders.Add("User-Agent", "YourWpfApp");
            //});

            // 或者，注册一个类型化客户端（更推荐的方式）
            services.AddHttpClient<IJiuChunTangService, JiuChunTangService>(client =>
            {
                client.BaseAddress = new Uri("https://test.jiuchuntang.cn/api/open-api/v1/");
                client.DefaultRequestHeaders.Accept.Clear();
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            }).ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler
                {
                    ServerCertificateCustomValidationCallback = (request, cert, chain, sslPolicyErrors) =>
                    {
                        Debug.WriteLine("=== 证书验证详情 ===");
                        Debug.WriteLine($"证书主题: {cert?.Subject}");
                        Debug.WriteLine($"证书颁发者: {cert?.Issuer}");
                        Debug.WriteLine($"证书有效期: {cert?.GetEffectiveDateString()} 到 {cert?.GetExpirationDateString()}");
                        Debug.WriteLine($"证书指纹: {cert?.GetCertHashString()}");
                        Debug.WriteLine($"SSL 策略错误: {sslPolicyErrors}");
                        Debug.WriteLine($"当前时间: {DateTime.Now}");

                        // 检查证书是否过期
                        if (cert != null)
                        {
                            if (DateTime.Now < cert.NotBefore)
                                Debug.WriteLine("证书尚未生效！");
                            if (DateTime.Now > cert.NotAfter)
                                Debug.WriteLine("证书已过期！");
                        }

                        Console.WriteLine("====================");

                        return true; // 暂时接受所有证书以获取详细信息，意味着不校验证书
                    }
                };
            });
        }
    }
}